<template>
  <div class="flex h-full flex-col">
    <div class="mb-4 flex justify-end">
      <el-button type="primary" :icon="Refresh" @click="handleSearch">刷新</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="flex h-0 grow flex-col">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
        class="h-0 grow"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="roleId" label="角色ID" width="80" />
        <el-table-column prop="roleName" label="角色名称" width="150" />
        <el-table-column prop="dataScope" label="数据权限范围" width="180">
          <template #default="{ row }">
            <el-tag :type="getDataScopeType(row.dataScope)">
              {{ getDataScopeName(row.dataScope) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="orgIds" label="自定义组织" min-width="200">
          <template #default="{ row }">
            <div v-if="row.dataScope === 5 && row.orgIds && row.orgIds.length > 0">
              <el-tag
                v-for="orgId in row.orgIds"
                :key="orgId"
                size="small"
                style="margin-right: 5px"
              >
                {{ getOrgName(orgId) }}
              </el-tag>
            </div>
            <span v-else class="text-gray-400">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(row)"
              :disabled="row.dataScope === 1"
            >
              重置
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-2 flex justify-end">
        <el-pagination
          v-model:current-page="pageParams.page"
          v-model:page-size="pageParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 编辑数据权限对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="`编辑数据权限 - ${currentRole?.roleName}`"
      width="600px"
      destroy-on-close
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <el-form-item label="角色名称">
          <el-input :value="currentRole?.roleName" disabled />
        </el-form-item>
        <el-form-item label="数据权限范围" prop="dataScope">
          <el-select
            v-model="formData.dataScope"
            placeholder="请选择数据权限范围"
            @change="handleDataScopeChange"
          >
            <el-option
              v-for="item in dataScopeOptions"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"
            >
              <span>{{ item.label }}</span>
              <span v-if="item.description" class="ml-2 text-xs text-(--el-text-color-secondary)">
                {{ item.description }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="formData.dataScope === 5" label="自定义组织" prop="orgIds">
          <el-tree-select
            v-model="formData.orgIds"
            :data="organizationTree"
            multiple
            :render-after-expand="false"
            show-checkbox
            check-strictly
            placeholder="请选择组织"
            node-key="id"
            :props="{ label: 'orgName', children: 'children' }"
            style="width: 100%"
          />
        </el-form-item>
        <el-alert
          :title="getDataScopeDescription(formData.dataScope)"
          type="info"
          :closable="false"
          class="mt-2.5"
        />
      </el-form>
      <template #footer>
        <div class="flex justify-end">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {
  deleteDataPermission,
  getDataPermissionList,
  updateDataPermission
} from '@/api/system/data-permission.api'
import { getOrganizationTree } from '@/api/system/organization.api'
import { getDict } from '@/utils/dict'
import { to } from '@/utils/promise'
import { Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'

// ==================== 状态管理 ====================
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)

// ==================== 表格数据 ====================
const tableData = ref<DataPermissionResponse[]>([])
const selectedRows = ref<DataPermissionResponse[]>([])
const total = ref(0)

// ==================== 分页参数 ====================
const pageParams = reactive({
  page: 1,
  pageSize: 10
})

// ==================== 字典数据 ====================
const dataScopeOptions = ref<Array<{ label: string; value: string; description?: string }>>([])
const dataScopeDictData = ref<DictData[]>([])

// ==================== 组织数据 ====================
const organizationTree = ref<any[]>([])
const organizationMap = ref<Map<number, string>>(new Map())

// ==================== 表单数据 ====================
const formRef = ref<FormInstance>()
const currentRole = ref<DataPermissionResponse | null>(null)
const formData = reactive<UpdateDataPermissionRequest>({
  dataScope: 1,
  orgIds: []
})

// ==================== 表单验证规则 ====================
const formRules = {
  dataScope: [{ required: true, message: '请选择数据权限范围', trigger: 'change' }],
  orgIds: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (formData.dataScope === 5 && (!value || value.length === 0)) {
          callback(new Error('自定义数据范围时必须选择组织'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// ==================== 字典数据加载 ====================
const loadDictData = async () => {
  const [dictError, dictData] = await to(getDict('data_scope'))
  if (!dictError && dictData) {
    dataScopeDictData.value = dictData
    dataScopeOptions.value = dictData.map((item) => ({
      label: item.dictLabel,
      value: item.dictValue,
      description: item.remark || ''
    }))
  }
}

// ==================== 数据获取 ====================
// 获取数据权限列表
const fetchDataPermissionList = async () => {
  loading.value = true
  const [error, response] = await to(getDataPermissionList())
  if (error || !response) {
    ElMessage.error('获取数据权限列表失败')
    loading.value = false
    return
  }
  tableData.value = response || []
  total.value = response?.length || 0
  loading.value = false
}

// 获取组织树
const fetchOrganizationTree = async () => {
  const [error, response] = await to(getOrganizationTree())
  if (error || !response) {
    ElMessage.error('获取组织树失败')
    return
  }
  organizationTree.value = response || []
  buildOrganizationMap(response || [])
}

// 构建组织映射
const buildOrganizationMap = (orgs: any[]) => {
  orgs.forEach((org) => {
    organizationMap.value.set(org.id, org.orgName)
    if (org.children && org.children.length > 0) {
      buildOrganizationMap(org.children)
    }
  })
}

// ==================== 辅助方法 ====================
// 获取组织名称
const getOrgName = (orgId: number): string => {
  return organizationMap.value.get(orgId) || `组织${orgId}`
}

// 获取数据权限范围名称
const getDataScopeName = (dataScope: number): string => {
  const item = dataScopeDictData.value.find((d) => d.dictValue === String(dataScope))
  return item?.dictLabel || String(dataScope)
}

// 获取数据权限范围类型
const getDataScopeType = (
  dataScope: number
): 'primary' | 'success' | 'warning' | 'info' | 'danger' | undefined => {
  const item = dataScopeDictData.value.find((d) => d.dictValue === String(dataScope))
  const listClass = item?.listClass || 'default'

  const typeMap: Record<string, 'primary' | 'success' | 'warning' | 'info' | 'danger' | undefined> =
    {
      primary: 'primary',
      success: 'success',
      warning: 'warning',
      info: 'info',
      danger: 'danger',
      default: undefined
    }

  return typeMap[listClass]
}

// 获取数据权限范围描述
const getDataScopeDescription = (dataScope: number): string => {
  const item = dataScopeDictData.value.find((d) => d.dictValue === String(dataScope))
  return item?.remark || ''
}

// ==================== 搜索和分页 ====================
// 搜索
const handleSearch = () => {
  pageParams.page = 1
  fetchDataPermissionList()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pageParams.pageSize = size
  pageParams.page = 1
  fetchDataPermissionList()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pageParams.page = page
  fetchDataPermissionList()
}

// 表格选择变化
const handleSelectionChange = (rows: DataPermissionResponse[]) => {
  selectedRows.value = rows
}

// ==================== CRUD 操作 ====================
// 编辑数据权限
const handleEdit = async (row: DataPermissionResponse) => {
  currentRole.value = row
  formData.dataScope = row.dataScope
  formData.orgIds = row.orgIds || []
  dialogVisible.value = true
}

// 删除（重置）数据权限
const handleDelete = (row: DataPermissionResponse) => {
  ElMessageBox.confirm(`确定要将角色"${row.roleName}"的数据权限重置为"全部数据"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const [error] = await to(deleteDataPermission(row.roleId))
    if (error) {
      ElMessage.error('重置失败')
      return
    }
    ElMessage.success('重置成功')
    fetchDataPermissionList()
  })
}

// ==================== 表单操作 ====================
// 数据权限范围变化
const handleDataScopeChange = (value: number) => {
  if (value !== 5) {
    formData.orgIds = []
  }
}

// 取消操作
const handleCancel = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  formData.dataScope = 1
  formData.orgIds = []
  formRef.value?.resetFields()
}

// 提交表单
const handleSubmit = async () => {
  if (!currentRole.value) return

  // 表单验证
  const valid = await formRef.value?.validate().catch(() => false)
  if (!valid) return

  submitLoading.value = true
  const [error] = await to(
    updateDataPermission(currentRole.value.roleId, {
      dataScope: formData.dataScope,
      orgIds: formData.dataScope === 5 ? formData.orgIds : []
    })
  )
  submitLoading.value = false

  if (error) {
    ElMessage.error('更新失败')
    return
  }

  ElMessage.success('更新成功')
  dialogVisible.value = false
  fetchDataPermissionList()
}

// ==================== 生命周期 ====================
onMounted(async () => {
  await loadDictData()
  fetchDataPermissionList()
  fetchOrganizationTree()
})
</script>

<style scoped></style>
